package sddz.foodmanage.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.foamtrace.photopicker.PhotoPickerActivity;
import com.google.gson.Gson;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Request;
import sddz.foodmanage.R;
import sddz.foodmanage.adapter.RecyclerAdapter;
import sddz.foodmanage.adapter.ViewHolder;
import sddz.foodmanage.base.BaseActivity;
import sddz.foodmanage.dialog.PhotoDialog;
import sddz.foodmanage.dialog.SortWindow;
import sddz.foodmanage.model.ClassifyBean;
import sddz.foodmanage.model.CommodityBean;
import sddz.foodmanage.model.UserStatusBean;
import sddz.foodmanage.utils.API;
import sddz.foodmanage.utils.HttpUtils;
import sddz.foodmanage.utils.SpfUtils;

import static sddz.foodmanage.dialog.PhotoDialog.PICK_FROM_CAMERA;
import static sddz.foodmanage.dialog.PhotoDialog.SELECT_PHOTO;

/**
 * @Date:2019/7/8
 * @Author:lbb 创建及修改食材
 */
public class CreationFoodActivity extends BaseActivity {


    @BindView(R.id.title_navigation_icon)
    ImageView titleNavigationIcon;
    @BindView(R.id.title_text)
    TextView titleText;
    @BindView(R.id.title_menu_icon)
    ImageView titleMenuIcon;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.image_title_right)
    ImageView imageTitleRight;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_unit)
    EditText etUnit;
    @BindView(R.id.et_price)
    EditText etPrice;
    @BindView(R.id.et_class)
    TextView etClass;
    @BindView(R.id.rb_up)
    RadioButton rbUp;
    @BindView(R.id.rb_down)
    RadioButton rbDown;
    @BindView(R.id.rg_choose_sex)
    RadioGroup rgChooseSex;
    @BindView(R.id.arl_status)
    AutoRelativeLayout arlStatus;
    @BindView(R.id.send_gather_rv)
    RecyclerView sendGatherRv;
    @BindView(R.id.all_image)
    AutoLinearLayout allImage;
    @BindView(R.id.image_add)
    ImageView imageAdd;
    @BindView(R.id.tv_create)
    TextView tvCreate;
    @BindView(R.id.activity_creation_food)
    AutoLinearLayout activityCreationFood;
    private SortWindow sortWindow;
    private String sortid;
    private PhotoDialog photoDialog;
    private ArrayList<String> mList = new ArrayList<>();//图片
    private RecyclerAdapter<String> mAdapter;
    private String imagePath;
    private CommodityBean.DataBeanX.DataBean databean;
    String status;//判断是创建还是修改的状态
    String stype;//判断上架还是下线状态

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_creation_food);
        ButterKnife.bind(this);
        initView();
        initData();
        initListener();
    }

    private void initData() {
        //获取类别数据
        getSortdata();
    }

    private void initListener() {
        //类别选择
        sortWindow.setOnNationItemListener(new SortWindow.OnNationItemListener() {
            @Override
            public void nation(String nation, String code) {
                sortid = code;
                etClass.setText(nation);
            }
        });
        //拍照
        photoDialog.setOnChoosePhotoListener(new PhotoDialog.OnChoosePhotoListener() {
            @Override
            public void openAlbum() {
                photoDialog.openAlbum(3-mList.size());
            }

            @Override
            public void openCamera() {
                if (mList.size() < 3) {
                    photoDialog.openCamera();
                } else {
                    show("图片已达到上限");
                }

            }
        });
    }


    private void initView() {
         status = getIntent().getStringExtra("status");

        sortWindow = new SortWindow(mActivity);
        photoDialog = new PhotoDialog(mActivity);
        mAdapter = new RecyclerAdapter<String>(mActivity, mList, R.layout.image_item_layout) {
            @Override
            protected void convert(ViewHolder holder, String s, final int position) {
                for(int aa=0;aa<mList.size();aa++){
                    if(!s.contains("http:")){
                        holder.setImageFile(mActivity, R.id.iv_item, s);
                    }else{
                        holder.setImageFile2(mActivity, R.id.iv_item, s);
                    }
                }

                if (mList.size() == 3) {
                    imageAdd.setVisibility(View.GONE);
                } else {
                    imageAdd.setVisibility(View.VISIBLE);
                }
                holder.getView(R.id.iv_delete).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mList.remove(position);
                        if (mList.size() == 0) {
                            sendGatherRv.setVisibility(View.GONE);
                            allImage.setVisibility(View.GONE);
                        } else {
                            sendGatherRv.setVisibility(View.VISIBLE);
                            allImage.setVisibility(View.VISIBLE);
                        }
                        if (mList.size() == 3) {
                            imageAdd.setVisibility(View.GONE);
                        } else {
                            imageAdd.setVisibility(View.VISIBLE);
                        }
                        mAdapter.notifyDataSetChanged();
                    }
                });

            }
        };
        sendGatherRv.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL));
        sendGatherRv.setAdapter(mAdapter);
        if (!TextUtils.isEmpty(status) && status.equals("true")) {
            titleText.setText("商品创建");
            arlStatus.setVisibility(View.GONE);
            sendGatherRv.setVisibility(View.GONE);
            allImage.setVisibility(View.GONE);
            tvCreate.setText("创建");
        } else {
            titleText.setText("食材修改");
            tvCreate.setText("修改");
            arlStatus.setVisibility(View.VISIBLE);
            sendGatherRv.setVisibility(View.VISIBLE);
            allImage.setVisibility(View.VISIBLE);
            databean= (CommodityBean.DataBeanX.DataBean) getIntent().getSerializableExtra("listdata");
            etName.setText(databean.getName());
            etUnit.setText(databean.getUnit());
            etPrice.setText(databean.getPrice()+"");
            etClass.setText(databean.getC_name()+"");
            sortid=databean.getClassification_id()+"";
            if(databean.getStatus()==1){
                rgChooseSex.check(R.id.rb_up);
            }else {
                rgChooseSex.check(R.id.rb_down);
            }
            if(mList!=null){
                mList.clear();
            }
            if(databean.getApiImgs().size()>0){
                for(int i=0;i<databean.getApiImgs().size();i++){
                    mList.add(databean.getApiImgs().get(i).getUrl());
                }
            }
            mAdapter.notifyDataSetChanged();
        }
    }

    @OnClick({R.id.title_navigation_icon, R.id.tv_create, R.id.et_class, R.id.image_add})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_navigation_icon:
                mActivity.setResult(RESULT_OK);
                finish();
                break;
            case R.id.tv_create://提交
                getSubmitData();
                break;
            case R.id.et_class://类别选择
                sortWindow.showWindow(view);
                break;
            case R.id.image_add://添加图片
                photoDialog.showDialog(view);
                break;
        }
    }

    /**
     * 创建
     */
    private void getSubmitData() {
        if (TextUtils.isEmpty(etName.getText().toString())) {
            show("请输入商品名称");
            return;
        }
        if (TextUtils.isEmpty(etUnit.getText().toString())) {
            show("请输入单位");
            return;
        }
        if (TextUtils.isEmpty(etPrice.getText().toString())) {
            show("请输入价格");
            return;
        }
        if (etClass.getText().toString().equals("请选择类别")) {
            show("请选择类别");
            return;
        }
       if(mList.size()==0){
           show("请上传图片");
           return;
       }
        dialog.show();
        Map<String, Object> map = new HashMap<>();
        map.put("name", etName.getText().toString());
        map.put("classification_id", sortid);
        map.put("unit", etUnit.getText().toString());
        map.put("price", etPrice.getText().toString());
        JSONObject object = new JSONObject(map);
        Log.e("创建商品数据", object.toString());
        for(int a=0;a<mList.size();a++){
            Log.e("mList", mList.size()+""+mList.get(a).toString());
        }

        if(!TextUtils.isEmpty(status)&&status.equals("true")) {
            HttpUtils.getInstance().UpFile(mActivity, API.getcreate, mList, object.toString(), SpfUtils.gettoken(mActivity), new HttpUtils.OnOkHttpCallback() {
                @Override
                public void onSuccess(final String body) {
                    dialog.dismiss();
                    Log.e("创建商品返回结果", body);
                    if (!TextUtils.isEmpty(body)) {
                        try {
                            JSONObject jsonObject = new JSONObject(body);
                            int code = jsonObject.optInt("status_code");
                            if (!jsonObject.optString("message").equals("")) {
                                show(jsonObject.optString("message"));
                            }
                            if (code == 200) {
                                mActivity.setResult(RESULT_OK);
                                finish();
                            } else if (code == 210) {
                                String token = jsonObject.optJSONObject("data").optString("token");
                                Log.e("33333333", token);
                                SpfUtils.savetoken(mActivity, token);
                                getSubmitData();
                            } else if (code == 401) {
                                SpfUtils.setLogin(mActivity, false);
                                startActivity(new Intent(mActivity, LoginActivity.class));
                                finish();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void onError(Request error, Exception e) {
                    dialog.dismiss();
                    show("提交失败，请稍后重试");
                }
            });
        }else{//修改
            int id = rgChooseSex.getCheckedRadioButtonId();
            if (id == R.id.rb_up) {
               stype = "1";
            } else {
                 stype = "2";
            }
            map.put("status",stype);
            JSONObject object2 = new JSONObject(map);
            Log.e("修改商品数据", object2.toString());
            Log.e("API.getspchange+databean.getId()", API.getspchange+databean.getId());
            HttpUtils.getInstance().UpFile(mActivity, API.getspchange+databean.getId(), mList, object2.toString(), SpfUtils.gettoken(mActivity), new HttpUtils.OnOkHttpCallback() {
                @Override
                public void onSuccess(final String body) {
                    dialog.dismiss();
                    Log.e("修改商品返回结果", body);
                    if (!TextUtils.isEmpty(body)) {
                        try {
                            JSONObject jsonObject = new JSONObject(body);
                            int code = jsonObject.optInt("status_code");
                            if (!jsonObject.optString("message").equals("")) {
                                show(jsonObject.optString("message"));
                            }
                            if (code == 200) {
                                mActivity.setResult(RESULT_OK);
                                finish();
                            } else if (code == 210) {
                                String token = jsonObject.optJSONObject("data").optString("token");
                                Log.e("33333333", token);
                                SpfUtils.savetoken(mActivity, token);
                                getSubmitData();
                            } else if (code == 401) {
                                SpfUtils.setLogin(mActivity, false);
                                startActivity(new Intent(mActivity, LoginActivity.class));
                                finish();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void onError(Request error, Exception e) {
                    dialog.dismiss();
                    show("提交失败，请稍后重试");
                }
            });
        }
    }

    //获取类别数据
    private void getSortdata() {
        HttpUtils.getInstance().GET(mActivity, API.getFenlei, SpfUtils.gettoken(mActivity), new HttpUtils.OnOkHttpCallback() {

            @Override
            public void onSuccess(String body) {
                Log.e("获取商品类别：", body);
                if (!TextUtils.isEmpty(body)) {
                    try {
                        JSONObject jsonObject = new JSONObject(body);
                        int code = jsonObject.optInt("status_code");
                        if (code == 200) {
                            ClassifyBean fenlei = new Gson().fromJson(body, ClassifyBean.class);
                            sortWindow.setData(fenlei.getData());
                        } else if (code == 210) {
                            String token = jsonObject.optJSONObject("data").optString("token");
                            SpfUtils.savetoken(mActivity, token);
                            getSortdata();
                        } else if (code == 401) {
                            SpfUtils.setLogin(mActivity, false);
                            startActivity(new Intent(mActivity, LoginActivity.class));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onError(Request error, Exception e) {

            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                //获取相册的照片
                case SELECT_PHOTO:
                    ArrayList<String> list = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
                    mList.addAll(list);
                    for(int q=0;q<mList.size();q++){
                        Log.e("mListqqqqqqqqqqqqqqqq",mList.get(q).toString());
                    }
                    sendGatherRv.setVisibility(View.VISIBLE);
                    allImage.setVisibility(View.VISIBLE);
                    if (mList.size() == 3) {
                        imageAdd.setVisibility(View.GONE);
                    } else {
                        imageAdd.setVisibility(View.VISIBLE);
                    }
                    mAdapter.notifyDataSetChanged();
                    break;
                //获取拍摄的照片
                case PICK_FROM_CAMERA:
                    imagePath = photoDialog.getImagePath();
                    if (!TextUtils.isEmpty(imagePath) && mList.size() < 3) {
                        mList.add(imagePath);
                    }
                    sendGatherRv.setVisibility(View.VISIBLE);
                    allImage.setVisibility(View.VISIBLE);
                    if (mList.size() == 3) {
                        imageAdd.setVisibility(View.GONE);
                    } else {
                        imageAdd.setVisibility(View.VISIBLE);
                    }
                    mAdapter.notifyDataSetChanged();
                    break;

            }
        }
    }


}
